package api

import (
	"fmt"
	"go-weiqi-system/config"
	"go-weiqi-system/internal/models"
	"go-weiqi-system/internal/utils"
	"time"

	"github.com/gin-gonic/gin"
)

type CompetitionRegistrationController struct{}

// Register 比赛报名
func (ctrl *CompetitionRegistrationController) Register(c *gin.Context) {
	userID, _ := c.Get("user_id")

	var req struct {
		CompetitionID     uint   `json:"competition_id" binding:"required"`
		ParticipantName   string `json:"participant_name" binding:"required"`
		ParticipantPhone  string `json:"participant_phone" binding:"required"`
		ParticipantIDCard string `json:"participant_id_card"`
		ParticipantAge    int    `json:"participant_age"`
		ParticipantLevel  string `json:"participant_level"`
		Remark            string `json:"remark"`
	}

	if err := c.ShouldBindJSON(&req); err != nil {
		utils.Error(c, "参数错误")
		return
	}

	// 检查比赛是否存在
	var competition models.Competition
	if err := config.DB.First(&competition, req.CompetitionID).Error; err != nil {
		utils.Error(c, "比赛不存在")
		return
	}

	// 检查比赛状态
	if competition.Status != 1 {
		utils.Error(c, "该比赛已关闭")
		return
	}

	// 检查人数限制
	if competition.MaxParticipants > 0 && competition.CurrentParticipants >= competition.MaxParticipants {
		utils.Error(c, "报名人数已满")
		return
	}

	// 生成报名编号
	registrationNo := fmt.Sprintf("R%d%d", time.Now().Unix(), userID)

	// 创建报名记录
	registration := models.CompetitionRegistration{
		UserID:            userID.(uint),
		CompetitionID:     req.CompetitionID,
		RegistrationNo:    registrationNo,
		ParticipantName:   req.ParticipantName,
		ParticipantPhone:  req.ParticipantPhone,
		ParticipantIDCard: req.ParticipantIDCard,
		ParticipantAge:    req.ParticipantAge,
		ParticipantLevel:  req.ParticipantLevel,
		Amount:            competition.Price,
		Status:            "待确认",
		Remark:            req.Remark,
	}

	if err := config.DB.Create(&registration).Error; err != nil {
		utils.Error(c, "报名失败")
		return
	}

	// 更新比赛人数
	config.DB.Model(&models.Competition{}).
		Where("id = ?", req.CompetitionID).
		Update("current_participants", config.DB.Raw("current_participants + ?", 1))

	utils.Success(c, registration, "报名成功")
}

// MyList 我的报名列表
func (ctrl *CompetitionRegistrationController) MyList(c *gin.Context) {
	userID, _ := c.Get("user_id")

	var param models.PageParam
	if err := c.ShouldBindQuery(&param); err != nil {
		param.Page = 1
		param.PageSize = 10
	}

	var registrations []models.CompetitionRegistration
	var total int64

	db := config.DB.Model(&models.CompetitionRegistration{}).
		Where("user_id = ?", userID).
		Preload("Competition")

	db.Count(&total)
	db.Order("id desc").
		Offset(param.GetOffset()).
		Limit(param.GetPageSize()).
		Find(&registrations)

	utils.Success(c, models.PageResponse{
		List:     registrations,
		Total:    total,
		Page:     param.GetPage(),
		PageSize: param.GetPageSize(),
	})
}

// CheckMyRegistrations 查询我在某比赛的报名记录
func (ctrl *CompetitionRegistrationController) CheckMyRegistrations(c *gin.Context) {
	userID, _ := c.Get("user_id")
	competitionID := c.Query("competition_id")

	if competitionID == "" {
		utils.Error(c, "参数错误")
		return
	}

	var registrations []models.CompetitionRegistration
	config.DB.Where("user_id = ? AND competition_id = ?", userID, competitionID).
		Find(&registrations)

	utils.Success(c, registrations)
}

// Detail 报名详情
func (ctrl *CompetitionRegistrationController) Detail(c *gin.Context) {
	userID, _ := c.Get("user_id")
	id := c.Query("id")

	if id == "" {
		utils.Error(c, "参数错误")
		return
	}

	var registration models.CompetitionRegistration
	if err := config.DB.Where("id = ? AND user_id = ?", id, userID).
		Preload("Competition").
		First(&registration).Error; err != nil {
		utils.Error(c, "报名记录不存在")
		return
	}

	utils.Success(c, registration)
}

// Cancel 取消报名
func (ctrl *CompetitionRegistrationController) Cancel(c *gin.Context) {
	userID, _ := c.Get("user_id")

	var req struct {
		ID uint `json:"id" binding:"required"`
	}

	if err := c.ShouldBindJSON(&req); err != nil {
		utils.Error(c, "参数错误")
		return
	}

	var registration models.CompetitionRegistration
	if err := config.DB.Where("id = ? AND user_id = ?", req.ID, userID).
		First(&registration).Error; err != nil {
		utils.Error(c, "报名记录不存在")
		return
	}

	if registration.Status == "已取消" {
		utils.Error(c, "该报名已取消")
		return
	}

	if registration.Status == "已确认" {
		utils.Error(c, "已确认的报名无法取消")
		return
	}

	// 更新状态
	if err := config.DB.Model(&registration).Update("status", "已取消").Error; err != nil {
		utils.Error(c, "取消失败")
		return
	}

	// 更新比赛人数
	config.DB.Model(&models.Competition{}).
		Where("id = ?", registration.CompetitionID).
		Update("current_participants", config.DB.Raw("current_participants - ?", 1))

	utils.Success(c, nil, "取消成功")
}
